﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Database.Context;
using QuanLyThongTinCoSo.Common;
using Model = Database.Models;

namespace QuanLyThongTinCoSo.Biz
{
    public class DoiBiz : BaseBiz
    {
        public DoiBiz()
        {
            DbContext = new Context();
        }

        public DoiBiz(Context context)
        {
            DbContext = context;
        }

        public override void Insert(Model.BaseModel model)
        {
            var doi = model as Model.Doi;
            doi.Created = DateTime.Now;
            doi.Modified = DateTime.Now;
            doi.CreatedBy = Utilities.CurrentUser();
            doi.ModifiedBy = Utilities.CurrentUser();

            DbContext.Dois.Add(doi);
            DbContext.SaveChanges();
        }

        public override void Update(Model.BaseModel model)
        {
            var doi = model as Model.Doi;
            doi.Modified = DateTime.Now;
            doi.ModifiedBy = Utilities.CurrentUser();

            DbContext.Entry(doi).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

        public override void Delete(Model.BaseModel model)
        {
            DbContext.Dois.Attach(model as Model.Doi);
            DbContext.Dois.Remove(model as Model.Doi);
            DbContext.Entry(model).State = EntityState.Deleted;

            DbContext.SaveChanges();
        }

        public override void DeleteItems(List<Model.BaseModel> models)
        {
            foreach (Model.Doi doi in models)
            {
                DbContext.Dois.Attach(doi);
                DbContext.Dois.Remove(doi);
                DbContext.Entry(doi).State = EntityState.Deleted;
            }

            DbContext.SaveChanges();
        }

        public override Model.BaseModel GetItemById(int id)
        {
            return (from item in DbContext.Dois
                    where item.Id == id
                    select item).First();
        }

        public Model.Doi GetDoiByName(string tenDoi)
        {
            return DbContext.Dois.FirstOrDefault(d => d.TenDoi == tenDoi);
        }

        public List<Model.Doi> GetAll()
        {
            return DbContext.Dois.OrderBy(d => d.TenDoi).ToList();
        }

        public List<Model.Doi> GetAllDoiByPhongId(int id)
        {
            return DbContext.Dois.Where(d => d.Phong != null && d.Phong.Id == id).OrderBy(d => d.TenDoi).ToList();
        }
    }
}